﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Dynamic;

namespace XW.Utils
{
    public class WXFWHHelper
    {
        private const string API_GETACCESSTOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
        private const string API_SENDMSG = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={0}";
        private static string ACCESS_TOKEN = "";
        private static DateTime getTokenTime = new DateTime(1990,01,01);
        /// <summary>
        ///  发布完成模板消息
        /// </summary>
        public static string PUBLISH_MSG_TEMPLATEID = "Qe5kSVwRfam0IpWqA9EJ_Ob-YYfDUZWgnrof5tYV26c";
        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns></returns>
        public static string GetAccessToken() {
            var now = DateTime.Now;
            if (getTokenTime > now && ACCESS_TOKEN.IsNotNullOrEmpty())
            {
                return ACCESS_TOKEN;
            }
            string url = string.Format(API_GETACCESSTOKEN, APPID, SECRET);
            var result = EasyHttp.With(url).GetForString();
            var jobj = JObject.Parse(result);
            if (jobj.ContainsKey("access_token"))
            {
                string access_token = jobj["access_token"].Value<string>();
                int expires_in = jobj["expires_in"].Value<int>();
                ACCESS_TOKEN = access_token;
                getTokenTime = now.AddSeconds(expires_in-10);
                return ACCESS_TOKEN;
            }
            else
            {
                ACCESS_TOKEN = "";
                throw new Exception(string.Format("获取公众号access_token异常，请联系管理员，错误内容：{0}", result));
            } 
        }
        /// <summary>
        /// 发送所有人消息
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static string SendMSGALL(string msg) {
            string token = GetAccessToken();
            string url = string.Format(API_SENDMSG, token);
            var result = EasyHttp.With(url).PostForJson(new {
                touser = GetOpenIds(),
                text = new {
                    content = msg
                },
                msgtype = "text"
            });
            var jobj = JObject.Parse(result);
            if (jobj.ContainsKey("errcode") && jobj["errcode"].Value<int>() == 0)
            {
                return "";
            }
            return result;
        }

        public static List<string> GetOpenIds(string next ="") {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}", GetAccessToken());
            if (next.IsNotNullAndEmpty())
            {
                url += string.Format("&next_openid={0}", next);
            }
            var result = EasyHttp.With(url).GetForString();
            List<string> opIds = new List<string>();
            if (next.IsNullOrEmpty())
            {
                var jObject = JObject.Parse(result);
               var ids = ((JArray)(jObject["data"]["openid"])).Select(c=>(string)c).ToList();
                opIds.AddRange(ids);
            }
            return opIds;
        }

        /// <summary>
        /// 获取模板Id
        /// </summary>
        /// <param name="template_id_short"></param>
        /// <returns></returns>
        public static string GetMSGTemplateId(string template_id_short) {

            string url = string.Format("https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={0}", GetAccessToken());
            var result = EasyHttp.With(url).PostForJson(new { template_id_short = template_id_short });
            var jObject = JObject.Parse(result);
            if (jObject.ContainsKey("errcode") && jObject["errcode"].Value<int>()== 0)
            {
                return jObject["template_id"].Value<string>();
            }
            throw new Exception(string.Format("获得模板ID异常，请联系管理员，错误内容：{0}", result));

        }

        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="msgId"></param>
        /// <param name="url"></param>
        /// <param name="parametes"></param>
        /// <returns></returns>
        public static string SendTemplateMsg(string openId,string msgId,string url,Dictionary<string,string> parametes) {
            dynamic obj = new ExpandoObject();
            obj.touser = openId;
            obj.template_id = msgId;
            obj.url = url;

            obj.data = new ExpandoObject();
            foreach (var item in parametes)
            {
                ((IDictionary<string, object>)obj.data).Add(item.Key, new { value = item.Value, color = "#173177" }); 
            }

            string urlSend = string.Format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}", GetAccessToken());
            var result = EasyHttp.With(urlSend).PostForJson(obj);

            return result;
        }
        /// <summary>
        /// 应用发布通知模板消息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="appName"></param>
        /// <param name="verionName"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public static List<string> SendAPPPublishMsgToAll(string url, string appName, string verionName, string remark) {
            var openIds = GetOpenIds();  
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters["first"] = string.Format("您好，应用【{0}】版本[{1}]已经发布完成。", appName, verionName);
            parameters["keyword1"] = appName;
            parameters["keyword2"] = verionName;
            parameters["keyword3"] = "由实际发布平台决定";
            parameters["keyword4"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            parameters["remark"] = remark;
            List<string> resultList = new List<string>();
            foreach (var openId in openIds)
            {
                var result = SendTemplateMsg(openId, PUBLISH_MSG_TEMPLATEID, url, parameters);
                resultList.Add(result);
            }
            return resultList;
        }
        //public static 
        public static string APPID
        {
            get
            {

                return ConfigHelper.GetApp("WXFWH:appid", "wxa8d6f64bff8cddbb");
            }
        }

        public static string SECRET
        {
            get
            {

                return ConfigHelper.GetApp("WXFWH:secret", "0263f9761f85dc6510635fa4aad72c21");
            }
        }
    }
}
